package com.sample.view;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.devnn.videoplayer.R;

public class VideoPlayer extends LinearLayout implements SeekBar.OnSeekBarChangeListener,View.OnClickListener,OnPreparedListener,OnCompletionListener,Handler.Callback,SurfaceHolder.Callback{
	private String TAG=this.getClass().getSimpleName();
	private View view;
	private Context context;
	private TextView tvCurrent,tvMax,tvTitle;
	private ImageView ivControl;
	private SeekBar seekBar;
	private String url;
	private SurfaceView surfaceView;
	private MediaPlayer mediaPlayer;
	private SurfaceHolder surfaceHolder;
	private View head,foot;
	private String dataPath=Environment.getExternalStorageDirectory().getPath()+File.separator+"test/test.mp4"; 
	//	private String dataPath="http://video.weibo.com/player/1034:58c3f9186fb046c767e056161c4bb010/v.swf"; 
	private Handler handler;
	private Timer timer=new Timer();
	private ImageView ivSize;
	private VideoSizeChangedListener videoSizeChangedListener;
	
	public void setVideoSizeChangedListener(
			VideoSizeChangedListener videoSizeChangedListener) {
		this.videoSizeChangedListener = videoSizeChangedListener;
	}
	public interface VideoSizeChangedListener{
		public void videoSizeChanged(boolean isProtraint);
	}
	public  VideoPlayer(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		this.context=context;
		handler=new Handler(this);
		view=LayoutInflater.from(context).inflate(R.layout.video_view,null);
		initView();
		this.addView(view);
	}
	private  TimerTask task=new TimerTask(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			handler.sendEmptyMessage(100);
		}

	};
	private void initView(){
		head=view.findViewById(R.id.play_head);
		foot=view.findViewById(R.id.play_foot);
		tvCurrent=(TextView) view.findViewById(R.id.play_current);
		tvMax=(TextView) view.findViewById(R.id.play_max);
		tvTitle=(TextView) view.findViewById(R.id.play_title);
		ivControl=(ImageView) view.findViewById(R.id.play_control);
		ivControl.setOnClickListener(this);
		seekBar=(SeekBar) view.findViewById(R.id.play_seek);
		ivSize=(ImageView) view.findViewById(R.id.play_size);
		ivSize.setOnClickListener(this);
		seekBar.setOnSeekBarChangeListener(this);
		surfaceView=(SurfaceView) view.findViewById(R.id.play_surface);
		surfaceView.setOnClickListener(this);
		surfaceHolder=this.surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		initSize();
	}
	private void initPlayer(){
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnPreparedListener(this);
		try {
			mediaPlayer.setDataSource(dataPath);
			mediaPlayer.setDisplay(surfaceHolder);
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.prepareAsync();
			timer.schedule(task, 0,1000);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			Tools.showTextToast(context, "格式不支持");
			e.printStackTrace();
		}

	}
	private void pause(){
		if(mediaPlayer !=null){  
			mediaPlayer.pause();
			ivControl.setImageResource(R.drawable.ic_play);
		} 
	}
	private void play(){
		if(mediaPlayer !=null){  
			mediaPlayer.start();
			ivControl.setImageResource(R.drawable.ic_pause);
			//			showInfo(false);
		} 

	}
	private void showInfo(boolean flag){
		if(flag){
			head.setVisibility(View.VISIBLE);
			foot.setVisibility(View.VISIBLE);
		}else{
			head.setVisibility(View.GONE);
			foot.setVisibility(View.GONE);
		}
	}
	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}
	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		Log.i(TAG, "surfaceCreated");
		initPlayer();
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		if(mediaPlayer.isPlaying()){
			mediaPlayer.stop();
		}
		mediaPlayer.release();
		task.cancel();
		timer.cancel();
	}
	@Override
	public void onCompletion(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		ivControl.setImageResource(R.drawable.ic_play);
	}
	private int videoWidth,videoHeight;
	private void initSize(){
		int screemWidth=this.getResources().getDisplayMetrics().widthPixels;
		int screemHeight=this.getResources().getDisplayMetrics().heightPixels;
		//		Log.i(TAG, "screemWidth:"+screemWidth);
		//		Log.i(TAG, "screemHeight:"+screemHeight);
		int bestHeight=screemWidth*9/16;
		//		Log.i(TAG, "bestHeight:"+bestHeight);
		ViewGroup.LayoutParams p=surfaceView.getLayoutParams();
		p.width=screemWidth;
		p.height=bestHeight;
		surfaceView.setLayoutParams(p);
	}
	public void setSize(boolean isPortraint){
		Log.i(TAG, "isPortraint:"+isPortraint);
		videoWidth = mediaPlayer.getVideoWidth();
		videoHeight = mediaPlayer.getVideoHeight();
		Log.i(TAG, "video width:"+videoWidth);
		Log.i(TAG, "video height:"+videoHeight);
		int screemWidth=this.getResources().getDisplayMetrics().widthPixels;
		int screemHeight=this.getResources().getDisplayMetrics().heightPixels;
		Log.i(TAG, "screemWidth:"+screemWidth);
		Log.i(TAG, "screemHeight:"+screemHeight);
		int bestHeight=screemWidth*videoHeight/videoWidth;
		Log.i(TAG, "bestHeight:"+bestHeight);
		ViewGroup.LayoutParams p=surfaceView.getLayoutParams();
		p.width=screemWidth;
		p.height=bestHeight;
		surfaceView.setLayoutParams(p);
		if(isPortraint){
			ivSize.setImageResource(R.drawable.ic_full);
		}else{
			ivSize.setImageResource(R.drawable.ic_nofull);
		}
	}
	private DecimalFormat format=new DecimalFormat("00");
	@Override
	public void onPrepared(MediaPlayer arg0) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onPrepared");
		if(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
			setSize(true);
		}else{
			setSize(false);
		}
		int max=mediaPlayer.getDuration();
		seekBar.setMax(max);
		int h=(int)(max/1000.0f/3600.0f);
		int m=(int)(max/1000.0f/60.0f)%60;
		int s=(int)(max/1000.0f)%60;
		tvMax.setText(format.format(h)+":"+format.format(m)+":"+format.format(s));
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0.equals(this.ivControl)){
			if(mediaPlayer.isPlaying()){
				pause();
			}else{
				play();
			}

		}else if(arg0.equals(this.surfaceView)){
			if(head.getVisibility()==View.VISIBLE){
				showInfo(false);
			}else{
				showInfo(true);
			}
		}else if(arg0.equals(this.ivSize)){
			if(videoSizeChangedListener!=null){
				videoSizeChangedListener.videoSizeChanged(!(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT));
			}
		}

	}
	@Override
	public boolean handleMessage(Message arg0) {
		// TODO Auto-generated method stub
		if(arg0.what==100){
			updateProgress();
		}
		return false;
	}
	private void updateProgress(){
		int position=mediaPlayer.getCurrentPosition();
		seekBar.setProgress(position);
		int h=(int)(position/1000.0f/3600.0f);
		int m=(int)(position/1000.0f/60.0f)%60;
		int s=(int)(position/1000.0f)%60;
		tvCurrent.setText(format.format(h)+":"+format.format(m)+":"+format.format(s));
	}
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		if(fromUser){
			mediaPlayer.seekTo(progress);
		}
	}
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		pause();
	}
	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		if(!mediaPlayer.isPlaying()){
			play();
		}
	}

}
